import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import GridContent from "@/components/PageHeaderWrapper/GridContent";
import { formatMessage } from "umi-plugin-react/locale";
import Ellipsis from "@/components/Ellipsis";
import { Row, Col, Card, Button, Table, Pagination, Modal, message, Input, Icon, List, Avatar, Divider, Tooltip } from "antd";
import styles from "./index.less";
import moment from "moment";
import tableDataCheck from "@/utils/isBackPrevPage";
import AddSystemKnowledge from "./add";
import UserSession from "@/UserSession";
import { routerRedux } from "dva/router";
import { robotCategoryAdd, robotCategoryList, robotCategoryDelete, robotCategoryDisabled, robotCategoryPublish, systemTemplatePublish, robotCategoryEdit } from "@/services/systemKnowledge";
import { knowledgeTemplateInfo } from "@/services/knowledgemanagement";
import ReferenceTemplate from "./referenceTemplate";
import QueryQaModal from "./queryQaModal";
import SortModal from "./sortModal";

const confirm = Modal.confirm;
@connect(({ customApi, loading }) => ({
	customApi,
	loading: loading.effects["customApi/fetch"],
}))
class SystemKnowledgeBase extends Component {
	constructor(props) {
		super(props);
		this.state = {
			current: 1,
			size: 16,
			tableLoading: false,
			list: [],
			total: 0,
			apiLoading: false,
			visible: false,
			isSystemKnowledge: false,
			detail: {}
		};
	}

	componentDidMount() {
		const { location: { params } } = this.props
		if (params && params.current) {
			this.setState({ isSystemKnowledge: UserSession.isSystemKnowledge(), tableLoading: true, current: params.current }, () => {
				this.getList();
			});
		} else {
			this.setState({ isSystemKnowledge: UserSession.isSystemKnowledge(), tableLoading: true }, () => {
				this.getList();
			});
		}

	}

	fanye = page => {
		this.setState({ current: page, tableLoading: true }, () => this.getList());
	}

	getList = async () => {
		const { current, size } = this.state;
		let res = null;
		if (UserSession.isSystemKnowledge()) {
			res = await knowledgeTemplateInfo({ current, size: 16 });
		} else {
			res = await robotCategoryList({
				current,
				size: 16,
				urlPrefix: UserSession.isSystemKnowledge() ? "headquarters" : null,
			});
		};
		this.setState({
			list: res.records,
			total: res.total,
			tableLoading: false,
		});
	};

	handleCreate = () => {
		const form = this.formRef.props.form;
		form.validateFields((err, values) => {
			if (err) {
				return;
			};
			// console.log(values);
			if (this.state.detail && this.state.detail.id) {
				this.doEditBaseName(values.name, values.type);
			} else {
				this.add(values.name, values.type);
			};
		});
	};

	add = async (name, type) => {
		const res = await robotCategoryAdd({
			name, type,
			urlPrefix: UserSession.isSystemKnowledge() ? "headquarters" : null,
		});
		this.setState({ visible: false, }, () => {
			this.getList();
		});
	};

	edit = async (id, name, row) => {
		let url = `/knowledgeDesign/myKnowledge/${id}/${row.type && row.type.length > 0 ? row.type[0] : 'file'}`;
		if (UserSession.isSystemKnowledge()) {
			url = `/knowledgeDesign/systemKnowledge/${id}/${row.type && row.type.length > 0 ? row.type[0] : 'file'}`;
		};
		const { history, location } = this.props;
		const { current } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			history.push({ pathname: url, query: { ...location.query, name, current } });
		});
	};

	reference = id => {
		if (this.referenceTemplateRef) {
			this.referenceTemplateRef.init(id)
		}
	}

	delete = async (id) => {
		confirm({
			title: UserSession.isAdmin() ? formatMessage({ id: 'systemKnowledgeBase.confirmDeleteTemplate' }) : formatMessage({ id: 'systemKnowledgeBase.confirmDelete' }),
			okText: formatMessage({ id: 'systemKnowledgeBase.confirm' }),
			cancelText: formatMessage({ id: 'systemKnowledgeBase.cancel' }),
			onOk: async () => {
				const res = await robotCategoryDelete({
					categoryId: id,
					urlPrefix: UserSession.isSystemKnowledge() ? "headquarters" : null,
				});
				message.success(res.message);
				this.getList();
			},
		});
	};

	disabled = async (id, disabled) => {
		confirm({
			title: disabled ? formatMessage({ id: 'systemKnowledgeBase.confirmDisableKnowledgeBase' }) : formatMessage({ id: 'systemKnowledgeBase.confirmEnableKnowledgeBase' }),
			okText: formatMessage({ id: 'systemKnowledgeBase.confirm' }),
			cancelText: formatMessage({ id: 'systemKnowledgeBase.cancel' }),
			onOk: async () => {
				const res = await robotCategoryDisabled({
					categoryId: id,
					urlPrefix: UserSession.isSystemKnowledge() ? "headquarters" : null,
					disabled,
				});
				message.success(res.message);
				this.getList();
			},
		});
	};

	publish = async (item) => {
		confirm({
			title: item.publish ? formatMessage({ id: 'systemKnowledgeBase.confirmUnpublishKnowledgeBase' }) : formatMessage({ id: 'systemKnowledgeBase.confirmPublishKnowledgeBase' }),
			okText: formatMessage({ id: 'systemKnowledgeBase.confirm' }),
			cancelText: formatMessage({ id: 'systemKnowledgeBase.cancel' }),
			onOk: async () => {
				const res = await robotCategoryDisabled({
					categoryId: item.id,
					disabled: !item.disabled ? 1 : 0,
				});
				message.success(res.message);
				this.getList();
			},
		});
	};

	uploadUpdate = async (id) => {
		// confirm({
		// 	title: "确定更新该知识库？",
		// 	okText: "确定",
		// 	cancelText: "取消",
		// 	onOk: async () => {
		const res = await systemTemplatePublish({ rootCategoryId: id });
		console.log(res);
		if (res?.data) {
			message.success(res.message);
			this.getList();
		};
		// 	},
		// });
	};

	saveFormRef = (formRef) => {
		this.formRef = formRef;
	};

	openQueryQaModal = () => {
		this.QueryQaModal.initOpenModal()
	}

	editBaseName = (item) => {
		this.setState({ visible: true, detail: item }, () => {
			setTimeout(() => {
				this.formRef.props.form.setFieldsValue({ name: item.name, type: item.type })
			}, 300)
		})
	}

	doEditBaseName = async (name, type) => {
		const res = await robotCategoryEdit({
			name, type,
			urlPrefix: UserSession.isSystemKnowledge() ? "headquarters" : null,
			id: this.state.detail.id
		});
		this.setState({ visible: false, detail: {} }, () => {
			this.getList();
		});
	}

	toggleBaseEditBtn = (flag, index) => {
		let { list } = this.state;
		list[index].showBaseEditButton = flag;
		this.setState({ list });
	}

	openSortModal = () => {
		this.SortModal.initModal()
	}

	render() {
		const { list, tableLoading, total, limit, visible, isSystemKnowledge, current } = this.state;
		const { history, location } = this.props;

		return (
			<GridContent>
				<Suspense fallback={<PageLoading />}>
					<PageHeaderWrapper>
						<Card className={styles.cardBody}>
							<div style={{ fontWeight: '500', color: '#333333' }}>
								{isSystemKnowledge ? (
									<div style={{ lineHeight: '32px', marginBottom: '15px' }}>{formatMessage({ id: 'systemKnowledgeBase.templateMarket' })}</div>
								) : (
									<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
										<span>{formatMessage({ id: 'systemKnowledgeBase.faqAndProcess' })}</span>
										<div>
											<Button type="primary" icon="plus" onClick={() => this.setState({ visible: true })} style={{ marginRight: 10 }}>{formatMessage({ id: 'systemKnowledgeBase.addKnowledgeBase' })}</Button>
											<Button icon="search" onClick={this.openQueryQaModal} style={{ marginRight: 10 }}>{formatMessage({ id: 'systemKnowledgeBase.queryKnowledge' })}</Button>
											<Button icon="unordered-list" onClick={this.openSortModal}>{formatMessage({ id: 'systemKnowledgeBase.sort' })}</Button>
										</div>
									</div>
								)}
							</div>
							<Divider />
							<div className={styles.cardList}>
								{isSystemKnowledge ? (
									<List
										rowKey='id'
										loading={tableLoading}
										pagination={{
											onChange: (page) => this.fanye(page),
											pageSize: 16,
											total,
											showQuickJumper: true,
											current
										}}
										grid={{ gutter: 16, xxl: 4, xl: 3,lg:2, md: 2, sm: 1, xs: 1 }}
										dataSource={list}
										renderItem={(item, index) => (
											<List.Item key={item.id}>
												<Card
													hoverable
													className={`${styles.cardItem} ${styles['card_' + index % 5]}`}
													actions={[
														<a onClick={() => this.edit(item.id, item.name, item)}>{formatMessage({ id: 'systemKnowledgeBase.view' })}</a>,
														<a onClick={() => this.reference(item.id)}>{formatMessage({ id: 'systemKnowledgeBase.referenceTemplate' })}</a>
													]}
												>
													<div
														style={{ margin: '-12px', marginLeft: '-5%', padding: '12px', paddingLeft: '5%' }}
														onClick={() => this.edit(item.id, item.name, item)}
													>
														<Card.Meta title={<a title={item.name}>{item.name}</a>} />
														<div style={{ color: '#000000', fontWeight: '500', height: '42px' }} />
													</div>
												</Card>
											</List.Item>
										)}
									/>
								) : (
									<List
										rowKey='id'
										loading={tableLoading}
										pagination={{
											onChange: (page) => this.fanye(page),
											pageSize: 16,
											total,
											showQuickJumper: true,
											current
										}}
										grid={{ gutter: 16, xxl: 4, xl: 3, md: 2, sm: 1 }}
										dataSource={list}
										renderItem={(item, index) =>
											<List.Item key={item.id}>
												<Card
													hoverable
													className={`${styles.cardItem} ${styles['cardMy_' + index % 5]}`}
													actions={UserSession.isAdmin() ? [
														<a onClick={() => this.uploadUpdate(item.id)}>{formatMessage({ id: 'systemKnowledgeBase.uploadUpdate' })}</a>,
														<a onClick={() => this.delete(item.id)}>{formatMessage({ id: 'systemKnowledgeBase.delete' })}</a>,
														<a onClick={() => this.edit(item.id, item.name, item)}>{formatMessage({ id: 'systemKnowledgeBase.edit' })}</a>,
													] : [
														<a onClick={() => this.delete(item.id)}>{formatMessage({ id: 'systemKnowledgeBase.delete' })}</a>,
														<a onClick={() => this.edit(item.id, item.name, item)}>{formatMessage({ id: 'systemKnowledgeBase.edit' })}</a>,
														<a onClick={() => this.disabled(item.id, !item.disabled ? 1 : 0)}>{item.disabled ? formatMessage({ id: 'systemKnowledgeBase.enable' }) : formatMessage({ id: 'systemKnowledgeBase.disable' })}</a>,
													]}
													onMouseEnter={() => this.toggleBaseEditBtn(true, index)}
													onMouseLeave={() => this.toggleBaseEditBtn(false, index)}
												>
													<div
														style={{ margin: '-12px', marginLeft: '-5%', padding: '12px', paddingLeft: '5%' }}
														onClick={() => this.edit(item.id, item.name, item)}
													>
														<Card.Meta
															title={<a title={item.name}>{item.name}</a>}
															description={
																UserSession.isAdmin() ? null : (
																	<Ellipsis
																		className={styles.item}
																		style={item.disabled ? {
																			background: '#FF9640',
																			borderColor: '#FF9640',
																		} : {
																			background: '#14C6A1',
																			borderColor: '#14C6A1',
																		}}
																		lines={3}
																	>
																		{item.disabled ? formatMessage({ id: 'systemKnowledgeBase.disabled' }) : formatMessage({ id: 'systemKnowledgeBase.enabled' })}
																	</Ellipsis>
																)
															}
														/>
														<div style={{ color: '#FFFFFF', fontWeight: '500', height: '42px' }}>
															{UserSession.isAdmin() && item.updateTime ? (
																<>
																	<span>{formatMessage({ id: 'systemKnowledgeBase.lastUpdateTime' })}</span>
																	<br />
																	<span>{moment(item.updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
																</>
															) : null}
														</div>
													</div>
												</Card>
											</List.Item>
										}
									/>
								)}
							</div>
						</Card>
						<AddSystemKnowledge
							wrappedComponentRef={this.saveFormRef}
							visible={visible}
							onCancel={() => this.setState({ visible: false })}
							onCreate={this.handleCreate}
						/>
						<ReferenceTemplate onRef={ref => this.referenceTemplateRef = ref} />
						<QueryQaModal onRef={ref => this.QueryQaModal = ref} history={history} location={location} />
						<SortModal onRef={ref => this.SortModal = ref} location={location} fetchList={this.getList} />
					</PageHeaderWrapper>
				</Suspense>
			</GridContent>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(SystemKnowledgeBase);
